# -*- coding: UTF-8 -*-
import json
import requests
from log.logUtils import logger
from utils import parse_config, tools

__author__ = 'Young'
'''
Don't try to read it. 
      I don't even know what I'm writing. Right
'''


class HttpRequests(object):
    """
    eg: request = HttpRequests()
        response = request(method, url, data)
        or
        response = request.send_request(method, url, data)
        print(response.text)
    """

    def __init__(self):

        self.header_form = {'Content-Type': 'application/x-www-form-urlencoded', 'charset': 'UTF-8'}
        self.header_json = {'Content-Type': 'application/json', 'charset': 'UTF-8'}
        self.session = requests.Session()

    def login(self):
        global token
        # parameter = {'username': self.user['username'], 'password': self.user["password"]}
        loginDict = {'code': parse_config.conf.getconf('login', 'login_code'),
                     'phone': parse_config.conf.getconf('login', 'login_phone')}
        data = {
            "loginType": 1,
            "phoneData": {
                "code": loginDict['code'],
                "phone": loginDict['phone']
            },
            "pid": 1,
            "platformType": 1,
            "registerSource": 1,
            "recommendId": "",
            "recommendName": "",
            "recommendUuid": ""
        }
        response = self.send_request(method='post',
                                     url='https://gateway-test.53zaixian.com/zs-user-api/zhushou/login',
                                     params_type='JSON', data=data)
        # keysAll_list = tools.checkJSON().getKeys(response.json())

        isFalse = tools.checkJSON().isExtend(response.json(), 'token')
        if not isFalse:
            raise KeyError('当前key取值不存在')
        token = response.json().get('data').get('token')['token']
        logger.info(response.json())
        logger.info("*" * 50)
        logger.info(token)
        '''
        self.token = response.json().has_key('data')
        if self.token:
            token = response.json()['data']['token']['token']
            print(response.json())
        else:
            raise  KeyError('token不存在')
        pass
        '''

    def send_request(self, method, url, params_type='json', data=None, **kwargs):
        method = method.upper()
        params_type = params_type.upper()
        if isinstance(data, str):
            try:
                data = json.loads(data)
            except Exception:
                data = eval(data)
        if 'GET' == method:
            response = self.session.request(method=method, url=url, params=data)
        elif 'POST' == method:
            if params_type == 'FORM':  # 发送表单数据，使用data参数传递
                response = self.session.request(method=method, url=url, data=data, headers=self.header_form)
            elif params_type == 'JSON':  # 如果接口支持application/json类型，则使用json参数传递
                response = self.session.request(method=method, url=url, json=data, headers=self.header_json)
                pass
            else:  # 如果接口需要传递其他类型的数据比如 上传文件，调用下面的请求方法
                response = self.session.request(method=method, url=url, headers=self.headers)
        # 如果请求方式非 get 和post 会报错，此处可以继续添加其他的请求方法
        else:
            raise ValueError('request method "{}" error ! please check'.format(method))
        return response

    def __call__(self, method, url, params_type='form', data=None, **kwargs):
        return self.send_request(method, url,
                                 params_type=params_type,
                                 data=data,
                                 **kwargs)

    def close_session(self):
        self.session.close()
        try:
            del self.session.cookies['JSESSIONID']
        except:
            pass


request = HttpRequests()

if __name__ == '__main__':
    request.login()
    data1 = {
        "loginType": 1,
        "phoneData": {
            "code": "0000",
            "phone": "14999999999"
        },
        "pid": 1,
        "platformType": 1,
        "registerSource": 1,
        "recommendId": "",
        "recommendName": "",
        "recommendUuid": ""
    }

    # example：
    headers = {'Content-Type': 'application/json;charset=UTF-8'}
    response = request.send_request(method='post', url='https://gateway-test.53zaixian.com/zs-user-api/zhushou/login',
                                    params_type='JSON', data=data1)
    # logger.info(response.json())
    # res = requests.post('https://gateway-test.53zaixian.com/zs-user-api/zhushou/login' ,data)
    # logger.info(res.json())
